package net.mycrub.bitwise.ocr.training;

import java.util.ArrayList;

import net.mycrub.bitwise.core.Brain;
import net.mycrub.bitwise.core.impl.LinearLayerFactory;
import net.mycrub.bitwise.core.impl.LowCutLayer;
import net.mycrub.bitwise.core.impl.PipelineLayer;
import net.mycrub.bitwise.core.util.Random;
import net.mycrub.bitwise.core.util.SerializationException;

import org.apache.log4j.Logger;

public class BrainFactory {
    private final static Logger LOGGER = Logger.getLogger(BrainFactory.class);
    
    public final static int BRAINS_PER_LIST = 50;
    public final static int NB_LISTS = 2000;


    public static Brain createBrain() {
        PipelineLayer pl = new PipelineLayer();

        pl.addLayer(LinearLayerFactory.createRandom(400, 100, -1, 1, 0.001, 0.005, 0.01, .5, .05));
        pl.addLayer(new LowCutLayer(100, 0., 1., .005, Random.next() * .7 + .3));
        pl.addLayer(LinearLayerFactory.createRandom(100, 80, -1, 1, 0.001, 0.005, 0.01, .5, .05));
        pl.addLayer(new LowCutLayer(80, 0., 1., .005, Random.next() * .7 + .3));
        pl.addLayer(LinearLayerFactory.createRandom(80, 10, -1, 1, 0.001, 0.005, 0.01, .5, .05));

        Brain brain = new Brain(randomName(10), pl);

        return brain;
    }
    
    private static String randomName(int length) {
        char[] chars = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ,'a', 'b', 'c', 'd', 'e', 'f'};
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append(chars[(int)(Random.next() * chars.length)]);
        }
        return sb.toString();
    }
    
    public static void createListsOfBrains(ListOfBrainsDAO dao) throws SerializationException {
        for(int l = 0; l < NB_LISTS; l++) {
            ListOfBrains brains = new ListOfBrains();
            brains.list = new ArrayList<Brain>();
            
            for (int b = 0; b < BRAINS_PER_LIST; b++) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Creating brain #" + b + " in list #" + l);
                }
                brains.list.add(BrainFactory.createBrain());
            }
            dao.saveOrUpdate(brains);
        }
    }
    
}
